package com.example.tpintegrador;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

import com.example.tpintegrador.MainActivity.Holder;
import com.example.tpintegrador.data.ContactDataBaseHelper;
import com.example.tpintegrador.entities.AndroidContact;
import com.example.tpintegrador.entities.Mail;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.QuickContactBadge;
import android.widget.TextView;
public class RegistroEmails extends ListActivity {

	private String idContacto;
	private String nombreContacto;
	private AndroidMailAdapter adapter;
	private boolean antiguo;
	private String filtro;
	private boolean filtroAplicado;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.registro_emails);
		adapter= new AndroidMailAdapter();
		setListAdapter(adapter);
		TextView n = (TextView) this.findViewById(R.id.txtContacto);
		ImageView photo = (ImageView) this.findViewById(R.id.fotoContacto);
		
		if (PreferenceManager.getDefaultSharedPreferences(this).getString("ordenRegistros", "DESC").compareTo("DESC") == 0) {
			antiguo = true;
		} else
			antiguo = false;
		
		Bundle extras = getIntent().getExtras();
		if (extras != null) {
			idContacto=extras.getString("idContacto");
			nombreContacto=extras.getString("nombreContacto");
			n.setText(nombreContacto);
			photo.setImageURI(Uri.parse(extras.getString("fotoContacto")));
		}		
		cargarMails();
	}
	
	private void reOrdenarMails(boolean reciente) {
		Comparator<Mail> comparator = null;
		if (reciente) {
			comparator = new CompararMailReciente();
		} else {
			comparator = new CompararMailAntiguo();
		}
		adapter.ordenar(comparator);
		adapter.notifyDataSetChanged();
	}

	class CompararMailReciente implements Comparator<Mail> {
		@Override
		public int compare(Mail lhs, Mail rhs) {
			return rhs.getFecha().compareTo(lhs.getFecha());
		}
	}

	class CompararMailAntiguo implements Comparator<Mail> {
		@Override
		public int compare(Mail lhs, Mail rhs) {
			return lhs.getFecha().compareTo(rhs.getFecha());
		}
	}

	public void cargarMails(){
		SharedPreferences myPreference = PreferenceManager.getDefaultSharedPreferences(this);
		Cursor cursor = null;
		Mail mail= new Mail();
		adapter.clear();
		
		ContactDataBaseHelper database= new ContactDataBaseHelper(this);
		cursor= database.getMailsOrdenados(idContacto, myPreference.getString("ordenRegistros", "DESC"));
		if (cursor != null) {
			if (cursor.moveToFirst()) {
				int date = cursor.getColumnIndex(ContactDataBaseHelper.colFecha);
				int subject = cursor.getColumnIndex(ContactDataBaseHelper.colAsunto);
				String filtro = PreferenceManager.getDefaultSharedPreferences(this).getString("filtroEmail", "f");
				do {
					String dato;
					if (filtro.equals("f")) {
						dato = cursor.getString(date);
					}
					else {
						dato = cursor.getString(subject);
					}
					
					if (dato != null
							&& (!filtroAplicado || dato.toLowerCase().startsWith(filtro))) {
					mail = new Mail();
					mail.setID(cursor.getInt(cursor.getColumnIndex("_id")));
					mail.setFecha(cursor.getString(date));
					mail.setAsunto(cursor.getString(subject));
					adapter.addEmail(mail);
					}
				} while (cursor.moveToNext());
				cursor.close();
			}
			adapter.notifyDataSetChanged();
	  }
	}
  
	
	 class Holder {
			private TextView txtFecha;
			private TextView txtAsunto;
		}
	
	class AndroidMailAdapter extends BaseAdapter implements Filterable {
		private ArrayList<Mail> mails;
		private LayoutInflater inflater;
		private FiltroMail filtroMail;
		
		public AndroidMailAdapter() {
			mails = new ArrayList<Mail>();
			inflater = LayoutInflater.from(RegistroEmails.this);
		}
		
		public void addEmail(Mail email) {
			if (email != null) {
				mails.add(email);
			}
		}

		@Override
		public int getCount() {
			return mails.size();
		}

		public void clear() {
			mails.clear();
		}

		@Override
		public Object getItem(int position) {
			return mails.get(position);
		}
		
		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup arg2) {
			Holder holder;
			if (convertView == null) {
				convertView = inflater
						.inflate(R.layout.registro_emails_item, null);
				holder = new Holder();
				holder.txtFecha = (TextView) convertView
						.findViewById(R.id.txtFecha);
				holder.txtAsunto = (TextView) convertView
						.findViewById(R.id.txtAsunto);
				convertView.setTag(holder);
			} 
			else {
				holder = (Holder) convertView.getTag();
			}
			
			Mail m = (Mail) getItem(position);
			holder.txtFecha.setText(m.getFecha());
			if (m.getAsunto().length() > 30) {
				holder.txtAsunto.setText(m.getAsunto().substring(0, 30)
						+ "...");
			} else {
				holder.txtAsunto.setText(m.getAsunto());
			}
			return convertView;
		}
		
		public void ordenar(Comparator<Mail> comparator) {
			Collections.sort(mails, comparator);
		}
		
		public Filter getFilter() {
			if (filtroMail == null) {
				filtroMail = new FiltroMail();
			}
			return filtroMail;
		}
		
		private void getFiltroAplicado() {
			if (filtro == null || filtro.length() == 0) {
				filtroAplicado = false;
			} else {
				filtroAplicado = true;
			}

			cargarMails();
		}
		
		class FiltroMail extends Filter {
			@Override
			protected FilterResults performFiltering(CharSequence constraint) {
				String filter = constraint.toString().toLowerCase().trim();
				filtro = filter;
				return null;
			}

			@Override
			protected void publishResults(CharSequence constraint, FilterResults results) {
				getFiltroAplicado();
			}
		}		
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		Boolean ordenActualReciente;
		if (PreferenceManager.getDefaultSharedPreferences(this)
				.getString("orderlog", "DESC").compareTo("DESC") == 0)
			ordenActualReciente = true;
		else
			ordenActualReciente = false;

		if (ordenActualReciente && !antiguo) {
			reOrdenarMails(true);
			antiguo = true;
		}
		if (!ordenActualReciente && antiguo) {
			reOrdenarMails(false);
			antiguo = false;
		}
		cargarMails();
	}
}
	

